package com.mikufufu.blog.service.impl;

import com.mikufufu.blog.common.enums.HtmlTemplate;
import com.mikufufu.blog.model.vo.admin.EmailConfig;
import com.mikufufu.blog.service.EmailService;
import com.mikufufu.blog.service.SysSettingService;
import com.mikufufu.blog.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private SysSettingService settingsService;

    private JavaMailSender mailSender() {

        EmailConfig emailConfig = settingsService.getMail();

        if (emailConfig == null) {
            throw new RuntimeException("请先设置邮件配置");
        }

        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(emailConfig.getHost());
        mailSender.setPort(emailConfig.getPort());
        mailSender.setUsername(emailConfig.getUsername());
        mailSender.setPassword(emailConfig.getPassword());
        mailSender.setDefaultEncoding("UTF-8");
        // ▼ 缺失关键SSL配置 ▼
        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", true);
        boolean sslEnable = emailConfig.getSslEnable() == 1;
        props.put("mail.smtp.ssl.enable", sslEnable);
        props.put("mail.smtp.connectiontimeout", 5000);
        props.put("mail.smtp.timeout", 5000);
        return mailSender;
    }

    @Override
    public void sendSimpleMail(String to, String subject, String text) {

        EmailConfig emailConfig = settingsService.getMail();

        if (emailConfig == null) {
            throw new RuntimeException("请先设置邮件配置");
        }

        JavaMailSender mailSender = mailSender();

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(emailConfig.getDefaultSender());
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        mailSender.send(message);
    }

    @Override
    public void sendHtmlEmail(String sender,String to, String subject, String content) {

        JavaMailSender mailSender = mailSender();
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);

        EmailConfig emailConfig = settingsService.getMail();

        if (emailConfig == null) {
            throw new RuntimeException("请先设置邮件配置");
        }

        try {
            // 设置发件人与收件人
            // setFrom()方法可以设置发件人的别名第一个参数是发件人邮箱，第二个参数是发件人别名
            helper.setFrom(emailConfig.getDefaultSender(),sender);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true); // 支持HTML
            mailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送失败", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("该编码不支持",e);
        }
    }

    @Override
    public void sendTemplateEmail(String sender, String to,  HtmlTemplate template, Map<String, String> values) {
        // 读取模版
        String subjectTemplate = getTemplate(template);
        if (StringUtils.isBlank(subjectTemplate)) {
            throw new RuntimeException("模版不存在");
        }
        // 替换模版
        String html = StringSubstitutor.replace(subjectTemplate, values);

        // 发送邮件
        sendHtmlEmail(sender, to, template.getSubject(), html);
    }

    /**
     * 读取模版
     *
     * @param template
     * @return
     */
    private String getTemplate(HtmlTemplate template) {
        ClassPathResource resource = new ClassPathResource("template/" + template.getFileName());
        try {
            // 使用 Apache Commons IO 读取流内容
            InputStream inputStream = resource.getInputStream();
            return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("读取模版邮件失败", e);
        }
        return "";
    }
}
